package com.zlzlib.libnetty.ws.handler;

import com.zlzlib.libnetty.listener.WebSocketListener;
import com.zlzlib.libnetty.util.Util;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketHandshakeException;
import io.netty.util.CharsetUtil;

public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {

    //握手工具
    private final WebSocketClientHandshaker handshake;
    private ChannelPromise handshakeFuture;
    private final WebSocketListener listener;

    public WebSocketClientHandler(WebSocketClientHandshaker handshake, WebSocketListener listener) {
        this.handshake = handshake;
        this.listener = listener;
    }

    public ChannelFuture handshakeFuture() {
        return handshakeFuture;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        handshakeFuture = ctx.newPromise();
        handshakeFuture.addListener(future -> {
            Util.logError(getClass().getName() + "=handshakeFuture: " + future.isSuccess());
        });
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        handshake.handshake(ctx.channel());
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        //判断握手是否完成
        if (!handshake.isHandshakeComplete()) {
            try {
                handshake.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
                handshakeFuture.setSuccess();
                listener.onOpen((FullHttpResponse) msg);
            } catch (WebSocketHandshakeException e) {
                handshakeFuture.setFailure(e);
                ctx.close();
                listener.onFailure(e, (FullHttpResponse) msg);
            }
            return;
        }
        if (msg instanceof FullHttpResponse) {
            FullHttpResponse response = (FullHttpResponse) msg;
            ctx.close();
            listener.onFailure(new IllegalStateException(
                    "Unexpected FullHttpResponse (getStatus=" + response.status() +
                            ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'), (FullHttpResponse) msg);
            return;
        }
        WebSocketFrame frame = (WebSocketFrame) msg;
        if (frame instanceof TextWebSocketFrame) {
            listener.onMessage(((TextWebSocketFrame) frame).text());
        } else if (frame instanceof BinaryWebSocketFrame) {
            listener.onMessage(frame.content().array());
        } else if (frame instanceof PongWebSocketFrame) {
            //服务器回传心跳
            listener.onHeartPong();
        } else if (frame instanceof CloseWebSocketFrame) {
            ctx.close();
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        ctx.close();
        Util.logError(getClass().getName() + "=断开连接");
        listener.onClosed(0, "断开连接");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        Util.logError(getClass().getName() + "=异常连接: " + cause.getMessage());
        if (!handshakeFuture.isDone()) {
            handshakeFuture.setFailure(cause);
        }
        ctx.close();
        listener.onFailure(cause, null);
    }

}
